package marchsoft.modules.tiku.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import marchsoft.base.PageVO;
import marchsoft.enums.ResultEnum;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.tiku.entity.*;

import marchsoft.modules.tiku.entity.dto.ERepositoryAndPracticeRecordDTO;
import marchsoft.modules.tiku.entity.dto.ERepositoryDto;
import marchsoft.modules.tiku.entity.dto.SelectRepositoryDto;
import marchsoft.modules.tiku.entity.excel.RepositoryExcel;
import marchsoft.modules.tiku.mapper.EPracticeRecordMapper;
import marchsoft.modules.tiku.mapper.ERepositoryMapper;
import marchsoft.modules.tiku.mapper.ESlideshowMapper;
import marchsoft.modules.tiku.mapper.EStudyDataMapper;
import marchsoft.modules.tiku.service.IERepositoryService;
import marchsoft.base.BasicServiceImpl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import marchsoft.modules.tiku.service.mapstruct.RepositoryMapStruct;
import marchsoft.utils.FileUtils;
import marchsoft.utils.RedisUtils;
import marchsoft.utils.SecurityUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;

/**
 * <p>
 * 题库 服务实现类
 * </p>
 *
 * @author zsy
 * @since 2022-03-29
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "repository")
public class ERepositoryServiceImpl extends BasicServiceImpl<ERepositoryMapper, ERepository> implements IERepositoryService {


    private final RepositoryMapStruct repositoryMapStruct;
    private final EPracticeRecordMapper ePracticeRecordMapper;
    private final ERepositoryMapper eRepositoryMapper;

    @Override
    public IPage<SelectRepositoryDto> getAll(SelectRepositoryDto repositoryDto, PageVO pageVO) {
        QueryWrapper<Object> query = new QueryWrapper<>();
//        System.out.println(repositoryDto);
        if(ObjectUtil.isNotNull(repositoryDto.getQuesContent())){
            query.and(e ->{
                e.like("er.ques_content",repositoryDto.getQuesContent());
            });
        }
        if(ObjectUtil.isNotNull(repositoryDto.getQuesType())){
            query.and(qw->qw.eq("er.ques_type",repositoryDto.getQuesType()));
        }
        if(ObjectUtil.isNotNull(repositoryDto.getSafeTypeId())){
            query.and(qw->qw.eq("er.safe_type_id",repositoryDto.getSafeTypeId()));
        }
        if(ObjectUtil.isNotNull(repositoryDto.getStartTime())){
            query.and(qw->qw.between("er.create_time",repositoryDto.getStartTime(),repositoryDto.getEndTime()));
        }
        query.eq("er.is_deleted",false);
        return eRepositoryMapper.getAll(pageVO.buildPage(),query);
    }

    @Override
    public void download(List<SelectRepositoryDto> repositoryDtoList, HttpServletResponse response) throws IOException {
        if (CollectionUtil.isEmpty(repositoryDtoList)) {
            throw new BadRequestException(ResultEnum.FILE_DOWNLOAD_FAIL_NOT_DATA);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for(SelectRepositoryDto repositoryDto:repositoryDtoList){
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号",repositoryDto.getId());
            map.put("题干",repositoryDto.getQuesContent());
            map.put("题型",repositoryDto.getQuesType());
            map.put("选项",repositoryDto.getOptions());
            map.put("参考答案",repositoryDto.getAnswer());
            map.put("题目类别",repositoryDto.getTypeName());
            map.put("出题时间",repositoryDto.getCreateTime() == null ? null : LocalDateTimeUtil.format(repositoryDto.getCreateTime()
                    , DatePattern.NORM_DATETIME_FORMATTER));
            list.add(map);
        }
        FileUtils.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRepository(List<RepositoryExcel> cachedDataList) {
        List<ERepository> excel = repositoryMapStruct.excel(cachedDataList);
        for (ERepository eRepository : excel){
            this.save(eRepository);
        }
//        System.out.println("插入的学生数据"+cachedDataList);
//        eRepositoryMapper.save(cachedDataList);

    }

    @Override
    public IPage<ERepository> getBySafeTypeId(PageVO pageVO, Long safeTypeId) {
        return eRepositoryMapper.getBySafeTypeId(pageVO.buildPage(),safeTypeId);
    }

    @Override
    @Cacheable(key = "'safeTypeId:'+#safeTypeId")
    public ERepositoryAndPracticeRecordDTO getRepositoryAndPracticeRecordIdBySafeTypeId(Long safeTypeId) {
        //声明返回的数据
        ERepositoryAndPracticeRecordDTO practiceRecordDTO=new ERepositoryAndPracticeRecordDTO();
        Long practiceRecordId=null;
        Long userId = SecurityUtils.getCurrentUserId();
        //查询联系记录表中该用户的分类数据
        List<EPracticeRecord> practiceRecordList=ePracticeRecordMapper.getByUserIdAndSafeTypeId(userId, safeTypeId);
        if (practiceRecordList.size() == 0) {
            EPracticeRecord ePracticeRecord = new EPracticeRecord();
            ePracticeRecord.setUserId(userId);
            ePracticeRecord.setSafeTypeId(safeTypeId);
            ePracticeRecordMapper.insert(ePracticeRecord);
            practiceRecordId = ePracticeRecord.getId();
        } else {
            practiceRecordId = practiceRecordList.get(0).getId();
        }
        LambdaQueryWrapper<ERepository> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ERepository::getSafeTypeId,safeTypeId);
        PageVO pageVO = new PageVO();
        // 查询该分类下所有的题库信息
        IPage<ERepositoryDto> dtoIPage = eRepositoryMapper.selectRepositoryPage(pageVO.buildPage(), queryWrapper);

        practiceRecordDTO.setPracticeRecordId(practiceRecordId);
        practiceRecordDTO.setERepositoryDTOS(dtoIPage.getRecords());

        return practiceRecordDTO;
    }

}

